﻿namespace nGo.Win.Wpf.Mef

open System
open System.ComponentModel.Composition
open System.ComponentModel.Composition.Hosting
open System.Windows

open Microsoft.Practices.ServiceLocation
open Microsoft.Practices.Prism.MefExtensions

[<Export>]
type public Shell() = 
    inherit Window()

type public Bootstrapper() = 
    inherit MefBootstrapper()

    override x.CreateShell() =
        x.Container.GetExportedValue<Shell>() :> DependencyObject

    override x.InitializeShell() =
        Application.Current.MainWindow <- x.Shell :?> Window
        Application.Current.MainWindow.Show()
        ()

    override x.ConfigureContainer() =
        base.ConfigureContainer()

        let locator = MefServiceLocatorAdapter(x.Container) :> IServiceLocator
        ServiceLocator.SetLocatorProvider((fun sloc -> locator))

        ()

    override x.ConfigureAggregateCatalog() =
        base.ConfigureAggregateCatalog()

        let assembly = x.GetType().Assembly
        let catalog = new AssemblyCatalog(assembly)
        x.AggregateCatalog.Catalogs.Add(catalog)

        ()

type public Application() =
    inherit System.Windows.Application()

    override x.OnStartup(args:StartupEventArgs) =
        let bootstrapper = Bootstrapper()
        bootstrapper.Run()
        ()

    static member Start() = Application().Run()